package com.zhongke.common.ext

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.kunminx.architecture.ui.callback.UnPeekLiveData
import com.zhongke.common.base.activity.ZKBaseActivity
import com.zhongke.core.http.httpbase.HttpResultState
import com.zhongke.core.http.httpbase.exception.AppException

/**
 *@Date: 2022/3/4
 *@Time: 18:00
 *@Author:cxc
 *@Description:
 */

/**
 * 显示页面状态，这里有个技巧，成功回调在第一个，其后两个带默认值的回调可省
 * @param resultState 接口返回值
 * @param onLoading 加载中
 * @param onSuccess 成功回调
 * @param onError 失败回调
 *
 */
fun <T> ZKBaseActivity<*, *>.parseState(
    resultState: HttpResultState<T>,
    onSuccess: (T) -> Unit,
    onError: ((AppException) -> Unit)? = null,
    onLoading: (() -> Unit)? = null
) {
    when (resultState) {
        is HttpResultState.Loading -> {
            showDialog(resultState.loadingMessage)
            onLoading?.run { this }
        }
        is HttpResultState.Success -> {
            dismissDialog()
            onSuccess(resultState.data)
        }
        is HttpResultState.Error -> {
            dismissDialog()
            onError?.run {
                this(resultState.error)
            }

        }
    }
}

/**
 *  liveData监听绑定，可以用onSuccess,onFailed监听结果
 * @param liveData  时间
 * @param listener  结果监听
 * 例如：observeState(viewModel.liveData){
 *    onSuccess{
 *    }
 *    onFailed{
 *    }
 * }
 */
fun <T> ZKBaseActivity<*, *>.observeState(liveData: UnPeekLiveData<HttpResultState<T>>, listener:HttpResultCallBack<T>.()->Unit){
    val httpCallBack =HttpResultCallBack<T>().apply { listener() }
    liveData.observe(this){resultState->
        when (resultState) {
            is HttpResultState.Loading -> {
                showDialog(resultState.loadingMessage)
                httpCallBack.loading?.invoke()
            }
            is HttpResultState.Success -> {
                dismissDialog()
                httpCallBack.success?.let { it(resultState.data) }
            }
            is HttpResultState.Error -> {
                dismissDialog()
                httpCallBack.failed?.invoke(resultState.error)

            }
        }
    }
}

/**
 * startActivity拓展
 * @receiver Activity
 * @param block 传递的intent内容
 */
inline fun <reified T> Activity.startActivity(block: Intent.() -> Unit = {}) {
    startActivity(Intent(this, T::class.java).apply(block))
}



class HttpResultCallBack<T> {
    var success:((T) -> Unit)? =null
    var failed:((AppException) ->Unit)? =null
    var loading:(() -> Unit)? = null

    fun onSuccess(call:(T)->Unit) {
        success = call
    }

    fun onFailed(call: (AppException) -> Unit){
        failed = call
    }

    fun onLoading(call: () -> Unit){
        loading = call
    }
}